package com.xrx.webtemplate.shiro;

import com.xrx.webtemplate.common.ShiroUser;
import com.xrx.webtemplate.utils.MD5;
import com.xrx.webtemplate.web.api.LoginApi;
import com.xrx.webtemplate.web.api.UserApi;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Created by xierongxian on 2017/4/23.
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private LoginApi loginApi;
    @Autowired
    private UserApi userApi;

    /**
     *shiro 授权 根据url授权
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        ShiroUser shiroUser =  (ShiroUser) principalCollection.getPrimaryPrincipal();
        //查询用户角色
        List<Map<String,String>> roleMap=userApi.searchUserRole(shiroUser.getId());
        //设置用户角色
        for(Map<String,String> m: roleMap){
            info.addRole(m.get("ROLE_NAME"));
        }
        HashSet<String> hashSet=new HashSet<String>();
        //查询用户权限菜单
        List<Map<String,String>> menuMap=userApi.searchMenu(shiroUser.getId());
        //设置用户权限url
        for(Map m:menuMap){
            if(m.get("URL")!=null&&!"".equals(m.get("URL"))){
                hashSet.add(m.get("URL").toString());
            }
        }
        info.setStringPermissions(hashSet);
        return info;
    }

    /**
     * shiro 认证用户信息
     *
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username=token.getPrincipal().toString();
        //获取凭证密码
        String password=new String((char[])token.getCredentials());
        //数据库验证邮箱密码是否存在
        String newpass=MD5.MD5(password);
        ShiroUser shiroUser=loginApi.checkLogin(username, MD5.MD5(password));
        if(shiroUser==null){
            throw new UnknownAccountException();
        }else{
            if (shiroUser.getState()!=1){
                //锁定停用
                throw new DisabledAccountException();
            }else{
                //保存用户信息到shiroSession
                Subject subject= SecurityUtils.getSubject();
                subject.getSession().setAttribute("shiroUser",shiroUser);
            }
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(shiroUser,shiroUser.getPassword(),this.getName());
        //info.setCredentialsSalt(ByteSource.Util.bytes(shiroUser.getUsername()));
        return info;
    }
}
